package cn.straosp.workrecord.service.impl

import cn.straosp.workrecord.bean.Account
import cn.straosp.workrecord.bean.AccountSelectFailed
import cn.straosp.workrecord.bean.LoginAccount
import cn.straosp.workrecord.bean.PhoneAlreadyRegistered
import cn.straosp.workrecord.bean.RegisterAccount
import cn.straosp.workrecord.dao.AccountDao
import cn.straosp.workrecord.db.AccountEntity
import cn.straosp.workrecord.db.toAccount
import cn.straosp.workrecord.service.AccountService
import cn.straosp.workrecord.util.Result
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.springframework.beans.factory.annotation.Autowired

class AccountServiceImpl : AccountService {

    @Autowired
    lateinit var accountDao: AccountDao

    override fun login(loginAccount: LoginAccount): Result<Account> {
        val accountEntity = accountDao.findOne { (it.phone eq loginAccount.phone) and (it.password eq loginAccount.password) }
            ?: return Result.Error(AccountSelectFailed)
        return Result.Success(accountEntity.toAccount())
    }

    override fun registerAccount(registerAccount: RegisterAccount): Result<Account> {
        val account = accountDao.findOne { it.phone eq registerAccount.phone }
        if (null != account) return Result.Error(PhoneAlreadyRegistered)
        val accountEntity = AccountEntity {
            phone = registerAccount.phone
            password = registerAccount.password
            username = registerAccount.username ?: registerAccount.phone
            header = registerAccount.header ?: ""
            sex = registerAccount.sex
            email = registerAccount.email ?: ""
            address = registerAccount.address ?: ""
        }
        accountDao.add(accountEntity)
        return Result.Success(accountEntity.toAccount())
    }

    override fun getAccountById(accountId: Int): Result<Account> {
        val accountEntity = accountDao.findOne { it.id eq accountId }
            ?: return Result.Error(AccountSelectFailed)
        return Result.Success(accountEntity.toAccount())
    }
}